// 修正版本的数据聚合模块
// 解决数据源不足的问题，采用分层数据架构

// 常量定义（可配置）
const CONFIG = {
    RETENTION: {
        HOURLY_DAYS: 1,     // hourly只保留当天（实时数据）
        DAILY_DAYS: 30,     // daily保留30天（持久化数据）
        WEEKLY_DAYS: 7,     // weekly基于daily计算最近7天
        MONTHLY_DAYS: 30,   // monthly基于daily计算最近30天
        YEARLY_MONTHS: 12   // yearly基于monthly计算最近12个月
    },
    PRECISION: 2            // 数值精度（小数位数）
};

// 工具函数：格式化数值
function formatNumber(value) {
    return Number(value.toFixed(CONFIG.PRECISION));
}

// 工具函数：生成日期范围
function generateDateRange(startDate, days) {
    const dates = [];
    for (let i = 0; i < days; i++) {
        const date = new Date(startDate);
        date.setDate(date.getDate() - i);
        dates.push(date.toISOString().slice(0, 10));
    }
    return dates;
}

// 工具函数：生成月份范围
function generateMonthRange(startDate, months) {
    const monthKeys = [];
    for (let i = 0; i < months; i++) {
        const date = new Date(startDate);
        date.setMonth(date.getMonth() - i);
        monthKeys.push(date.toISOString().slice(0, 7));
    }
    return monthKeys;
}

// 调试函数
function debugLog(message, data) {
    node.warn(`AGGREGATE DEBUG - ${message}: ${JSON.stringify(data)}`);
}

// 数据聚合核心类
class LayeredDataAggregator {
    constructor(existingStats) {
        this.existingStats = existingStats || { byTimeDimension: {} };
        this.currentDate = new Date();
        this.currentDay = this.currentDate.toISOString().slice(0, 10);
        this.currentMonth = this.currentDate.toISOString().slice(0, 7);
    }

    // 从当天hourly数据计算daily数据
    calculateTodayDaily() {
        debugLog('Calculating today daily from hourly', { currentDay: this.currentDay });
        
        const hourlyData = this.existingStats.byTimeDimension.hourly || {};
        const todayDaily = {};
        
        Object.keys(hourlyData).forEach(hourKey => {
            if (hourKey.startsWith(this.currentDay)) {
                const hourData = hourlyData[hourKey];
                Object.keys(hourData).forEach(pointId => {
                    if (!todayDaily[pointId]) {
                        todayDaily[pointId] = 0;
                    }
                    // 累加该测点当天所有小时的sum值
                    todayDaily[pointId] = formatNumber(todayDaily[pointId] + hourData[pointId].stats.sum);
                });
            }
        });

        return todayDaily;
    }

    // 更新并维护daily数据（持久化存储）
    updateDailyData() {
        debugLog('Updating daily data with persistence', null);
        
        // 获取现有的daily数据
        const existingDaily = this.existingStats.byTimeDimension.daily || {};
        
        // 计算今天的daily数据
        const todayDaily = this.calculateTodayDaily();
        
        // 更新今天的数据
        existingDaily[this.currentDay] = todayDaily;
        
        // 清理过期的daily数据（保留30天）
        const retentionDates = generateDateRange(this.currentDate, CONFIG.RETENTION.DAILY_DAYS);
        const cleanedDaily = {};
        
        retentionDates.forEach(date => {
            if (existingDaily[date]) {
                cleanedDaily[date] = existingDaily[date];
            }
        });
        
        debugLog('Daily data updated', {
            todayPoints: Object.keys(todayDaily).length,
            totalDays: Object.keys(cleanedDaily).length
        });
        
        return cleanedDaily;
    }

    // 基于daily数据计算weekly聚合
    calculateWeeklyFromDaily(dailyData) {
        debugLog('Calculating weekly from daily data', null);
        
        const weeklyData = {};
        const weeklyTotal = {};
        const dates = generateDateRange(this.currentDate, CONFIG.RETENTION.WEEKLY_DAYS);
        
        // 收集最近7天的daily数据
        dates.forEach(date => {
            if (dailyData[date]) {
                weeklyData[date] = dailyData[date];
                
                // 累加到总计
                Object.keys(dailyData[date]).forEach(pointId => {
                    if (!weeklyTotal[pointId]) {
                        weeklyTotal[pointId] = 0;
                    }
                    weeklyTotal[pointId] = formatNumber(weeklyTotal[pointId] + dailyData[date][pointId]);
                });
            }
        });

        return {
            days: weeklyData,
            total: weeklyTotal
        };
    }

    // 基于daily数据计算monthly聚合
    calculateMonthlyFromDaily(dailyData) {
        debugLog('Calculating monthly from daily data', null);
        
        const monthlyData = {};
        const monthlyTotal = {};
        const dates = generateDateRange(this.currentDate, CONFIG.RETENTION.MONTHLY_DAYS);
        
        // 收集最近30天的daily数据
        dates.forEach(date => {
            if (dailyData[date]) {
                monthlyData[date] = dailyData[date];
                
                // 累加到总计
                Object.keys(dailyData[date]).forEach(pointId => {
                    if (!monthlyTotal[pointId]) {
                        monthlyTotal[pointId] = 0;
                    }
                    monthlyTotal[pointId] = formatNumber(monthlyTotal[pointId] + dailyData[date][pointId]);
                });
            }
        });

        return {
            days: monthlyData,
            total: monthlyTotal
        };
    }

    // 基于daily数据计算monthly汇总，然后计算yearly
    calculateYearlyFromDaily(dailyData) {
        debugLog('Calculating yearly from daily data', null);
        
        const yearlyData = {};
        const yearlyTotal = {};
        const monthKeys = generateMonthRange(this.currentDate, CONFIG.RETENTION.YEARLY_MONTHS);
        
        // 按月汇总daily数据
        monthKeys.forEach(monthKey => {
            const monthTotal = {};
            
            // 找到该月的所有daily数据
            Object.keys(dailyData).forEach(date => {
                if (date.startsWith(monthKey)) {
                    Object.keys(dailyData[date]).forEach(pointId => {
                        if (!monthTotal[pointId]) {
                            monthTotal[pointId] = 0;
                        }
                        monthTotal[pointId] = formatNumber(monthTotal[pointId] + dailyData[date][pointId]);
                    });
                }
            });
            
            if (Object.keys(monthTotal).length > 0) {
                yearlyData[monthKey] = monthTotal;
                
                // 累加到年度总计
                Object.keys(monthTotal).forEach(pointId => {
                    if (!yearlyTotal[pointId]) {
                        yearlyTotal[pointId] = 0;
                    }
                    yearlyTotal[pointId] = formatNumber(yearlyTotal[pointId] + monthTotal[pointId]);
                });
            }
        });

        return {
            months: yearlyData,
            total: yearlyTotal
        };
    }

    // 执行完整的分层聚合
    performLayeredAggregation() {
        const startTime = Date.now();
        
        debugLog('Starting layered aggregation', null);
        
        // 1. 更新daily数据（基于hourly，持久化存储）
        const updatedDaily = this.updateDailyData();
        
        // 2. 基于daily数据计算其他维度
        const weeklyResult = this.calculateWeeklyFromDaily(updatedDaily);
        const monthlyResult = this.calculateMonthlyFromDaily(updatedDaily);
        const yearlyResult = this.calculateYearlyFromDaily(updatedDaily);
        
        const result = {
            daily: updatedDaily,
            weekly: weeklyResult,
            monthly: monthlyResult,
            yearly: yearlyResult,
            metadata: {
                lastUpdated: this.currentDate.toISOString(),
                processingTime: Date.now() - startTime,
                dataAvailability: {
                    dailyDays: Object.keys(updatedDaily).length,
                    weeklyDays: Object.keys(weeklyResult.days).length,
                    monthlyDays: Object.keys(monthlyResult.days).length,
                    yearlyMonths: Object.keys(yearlyResult.months).length
                }
            }
        };

        debugLog('Layered aggregation completed', result.metadata);
        return result;
    }
}

// 主执行逻辑
try {
    // 获取现有统计数据
    const existingStats = global.get('_STATISTICS_') || { byTimeDimension: {} };
    
    // 验证hourly数据是否存在
    if (!existingStats.byTimeDimension || !existingStats.byTimeDimension.hourly) {
        node.warn("No hourly data found for aggregation");
        return msg;
    }

    debugLog('Starting layered aggregation process', {
        hourlyDataKeys: Object.keys(existingStats.byTimeDimension.hourly).length,
        existingDailyDays: Object.keys(existingStats.byTimeDimension.daily || {}).length
    });

    // 创建分层聚合器并执行聚合
    const aggregator = new LayeredDataAggregator(existingStats);
    const aggregatedData = aggregator.performLayeredAggregation();

    // 更新统计数据结构
    const updatedStats = {
        byMeasurementPoint: existingStats.byMeasurementPoint || {},
        byTimeDimension: {
            hourly: existingStats.byTimeDimension.hourly,    // 保留原有小时数据（当天）
            daily: aggregatedData.daily,                     // 持久化的daily数据（30天）
            weekly: aggregatedData.weekly.days,              // 基于daily计算的最近7天
            monthly: aggregatedData.monthly.days,            // 基于daily计算的最近30天
            yearly: aggregatedData.yearly.months             // 基于daily计算的最近12个月
        },
        lastUpdated: aggregatedData.metadata.lastUpdated,
        // 汇总数据，供API查询使用
        aggregationSummary: {
            weeklyTotal: aggregatedData.weekly.total,        // 7天总计
            monthlyTotal: aggregatedData.monthly.total,      // 30天总计
            yearlyTotal: aggregatedData.yearly.total         // 12个月总计
        },
        aggregationMetadata: aggregatedData.metadata
    };

    // 保存更新后的统计数据
    global.set('_STATISTICS_', updatedStats);

    debugLog('Layered aggregation process completed successfully', {
        totalProcessingTime: aggregatedData.metadata.processingTime,
        dataAvailability: aggregatedData.metadata.dataAvailability
    });

} catch (error) {
    node.error("Error in layered aggregation process: " + error.message);
    node.warn(error.stack);
}

return msg;